package com.czh.auth.domain.service.impl;

import com.alibaba.fastjson2.JSON;
import com.czh.auth.common.constants.AuthConstant;
import com.czh.auth.common.constants.RedisKeyConstant;
import com.czh.auth.common.enums.AuthIsShowEnums;
import com.czh.auth.common.enums.AuthStatusEnums;
import com.czh.auth.domain.convert.AuthPermissionDomainConverter;
import com.czh.auth.domain.entity.AuthPermissionBO;
import com.czh.auth.domain.redis.RedisUtil;
import com.czh.auth.domain.service.AuthPermissionDomainService;
import com.czh.auth.infra.basic.entity.AuthPermission;
import com.czh.auth.infra.basic.service.AuthPermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author caozaihui
 * @version 1.0
 * @since 2024/8/30 下午 8:46
 */
@Service
public class AuthPermissionDomainServiceImpl implements AuthPermissionDomainService {

    @Resource
    private AuthPermissionService authPermissionService;

    @Resource
    private RedisUtil redisUtil;
    @Override
    public Boolean addPermission(AuthPermissionBO authPermissionBO) {
        AuthPermission authPermission = AuthPermissionDomainConverter.INSTANCE.convert(authPermissionBO);
        authPermission.setStatus(AuthStatusEnums.NORMAL.getCode());
        authPermission.setIsShow(AuthIsShowEnums.SHOW.getCode());
        return authPermissionService.insert(authPermission)>0;
    }

    @Override
    public Boolean updatePermission(AuthPermissionBO authPermissionBO) {
        return authPermissionService.update(AuthPermissionDomainConverter.INSTANCE.convert(authPermissionBO))>0;
    }

    @Override
    public Boolean deletePermission(Long id) {
        return authPermissionService.removeById(id);
    }

    @Override
    public List<String> getPermission(String username) {
        List<Object> cacheList = redisUtil.getCacheList(redisUtil.buildKey(RedisKeyConstant.authPermissionPrefix, username));
        List<AuthPermission> authPermissions = JSON.parseArray(cacheList.toString(), AuthPermission.class);
        return authPermissions.stream().map(AuthPermission::getPermissionKey).toList();
    }
}
